/**
 * 
 */
package info.niwota.webagent;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.xmpp.Presence;
import com.google.appengine.api.xmpp.PresenceType;
import com.google.appengine.api.xmpp.Subscription;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

/**
 * 
 * @author qiangli
 * 
 */
@SuppressWarnings("serial")
public class XMPPServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(XMPPServlet.class
			.getName());
	private static final XMPPService xmpp = XMPPServiceFactory.getXMPPService();

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			String uri = req.getRequestURI();

			if (uri.startsWith("/_ah/xmpp/subscription/")) {
				Subscription sub = xmpp.parseSubscription(req);

				log.fine("subscription: " + sub.getFromJid());
			}

			if (uri.startsWith("/_ah/xmpp/presence/")) {
				Presence presence = xmpp.parsePresence(req);

				xmpp.sendPresence(presence.getFromJid(), PresenceType.AVAILABLE,
						presence.getPresenceShow(), presence.getStatus());
				
				log.fine("presence: " + presence.getFromJid());
			}

		} catch (Exception e) {
			log.log(Level.SEVERE, e.getMessage());
		}
	}
}
